package cn.amebius.simpledocker.scheduled;

import cn.amebius.simpledocker.config.DockerFactory;
import cn.amebius.simpledocker.entity.model.DockerClientModel;
import cn.amebius.simpledocker.entity.po.DockerPo;
import com.github.dockerjava.api.DockerClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * docker容器的定时任务
 * @author 阿伟
 * @date 2023/7/31 16:33
 */

@Component
@EnableScheduling    //开启定时任务
@Slf4j
public class DockerClientTask {

    @Autowired
    DockerFactory dockerFactory;

    private Integer times = 0;


    private static final Long LATE_TIME = 5 * 60 * 1000L;//容器启动后,延迟秒数五分钟

    private static final Long FIX_TIME = 5 * 60 * 1000L; //多少秒再次执行，五分钟执行一次


    @Async
    @Scheduled(initialDelay = 1 * 60 * 1000L, fixedRate = 1 * 60 * 1000L)
    public void dockerResetTask() {
        times++;
        log.info("定时任务：dockerResetTask执行,第{}次执行",times);
        dockerFactory.setTaskTimes(times);
        Integer deads = 0;
        Integer alives = 0;
        Map<Integer, DockerClientModel> cg = dockerFactory.getClientGroup();
        Set<Integer> keys = cg.keySet();
        for (Integer key : keys) {
            DockerClientModel dcm = cg.get(key);
            if (dockerFactory.pingDockerClient(dcm)) {
                if (!dcm.getAlive()) {
                    dcm.setAlive(true);
                    cg.put(key,dcm);
                }
                alives++;
            } else {
                if (dcm.getAlive()) {
                    dcm.setAlive(false);
                    cg.put(key,dcm);
                }
                deads++;
            }
        }
        dockerFactory.setAlives(alives);
        dockerFactory.setDeads(deads);
        dockerFactory.broadcastStatus();
    }


}
